import json
import re

from django import http
from http import HTTPStatus

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views import View
from django.views.decorators.csrf import csrf_exempt

#from meidou_mall import settings
from django.conf import settings
from meidou_mall.apps.users.models import User, Address
from django.contrib.auth import authenticate, login, logout

from meidou_mall.utils.my_encrypt import generate_verify_url
from meidou_mall.utils.my_loginview import LoginRequiredView
from meidou_mall.utils.response_code import RET
from django.core.mail import send_mail


#from users.models import User


# Create your views here.

class RegisterView(View):
    def get(self,request):
        return render(request, 'register.html')

    def post(self,request):
        user_name = request.POST.get('user_name')
        pwd = request.POST.get('pwd')
        cpwd = request.POST.get('cpwd')
        phone = request.POST.get('phone')
        msg_code = request.POST.get('msg_code')
        allow = request.POST.get('allow')

        if not all([user_name,pwd, cpwd, phone, msg_code, allow]):
            return http.HttpResponseForbidden("参数不全")
            #return HttpResponse('参数不全', status=HTTPStatus.FORBIDDEN)

        if pwd != cpwd:
            return http.HttpResponseForbidden("两次密码不一致")

        if not re.match(r'^1[3-9]\d{9}$', phone):
            return http.HttpResponseForbidden("手机号格式有误")

        print("msg_code = %s".format(msg_code))

        if allow != 'on':
            return http.HttpResponseForbidden("协议需要同意")

        User.objects.create_user(username = user_name,  password = pwd, mobile=phone)

        return redirect('/')


class CheckUsernameCountView(View):
    def get(self,request, username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'count':count, "code":0})

class CheckMobileCountView(View):
    def get(self,request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'count':count, "code":0})



class LoginView(View):
    def get(self,request):
        return render(request, "login.html")

    def post(self,request):
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        remembered = request.POST.get('remembered')

        if not all([username, pwd]):
            return http.HttpResponseForbidden("参数不全")

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden("用户名格式不对")

        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return http.HttpResponseForbidden("密码格式不对")

        user = authenticate(request, username=username, password=pwd)

        if not user:
            return http.HttpResponseForbidden("用户名或密码不正确")

        login(request, user)
        if(remembered == 'on'):
            request.session.set_expiry(3600*24*2)
        else:
            request.session.set_expiry(0)

        response = redirect("/")
        response.set_cookie("username", user.username, max_age=3600*24*2)
        return response
        #return redirect('/')
        #return render(request, "/")

class LogoutView(View):
    def get(self,request):
        logout(request)
        response = redirect("/")
        response.delete_cookie("username")
        return response

class UserInfoView(LoginRequiredView):
    def get(self,request):
        # if request.user.is_authenticated:
        #     return render(request, "user_center_info.html")
        # else:
        #     return redirect("/")
        context = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
        }
        return render(request, "user_center_info.html", context)

class EmailView(LoginRequiredView):
    def put(self,request):
        email = json.loads(request.body.decode()).get("email")
        if not email:
            return http.JsonResponse({"code": RET.PARAMERR, "errmsg": "擦拭农户不全"})

        #verify_url = generate_verify_url(request.user, email)
        result = send_mail(subject='美多商场，验证链接', message="verify_url", recipient_list=['ciwenlong@163.com'],
                  from_email=settings.EMAIL_HOST_USER,)

        if result != 1:
            return http.JsonResponse({"code": RET.THIRDERR, "errmsg": "邮件发送失败"})

        request.user.email = email
        request.user.save()

        return http.JsonResponse({"code": RET.OK, "errmsg": "发送成功"})

class VerifyEmailView(View):
    def put(self,request):
        pass


class AddressView(LoginRequiredView):
    def get(self,request):
        addresses = request.user.addresses.filter(is_deleted=False).all()
        address_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id,
            }
            address_list.append(address_dict)
        context = {
            "addresses": address_list,
        }
        return render(request, "user_center_site.html", context=context)


class AddressesCreateView(View):

    def post(self,request):
        data_dict = json.loads(request.body.decode())
        title = data_dict.get("title")
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        if not all([title, receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({"code": RET.PARAMERR, "errmsg": "参数不正确"})

        data_dict["user_id"] = request.user.id
        address = Address.objects.create(**data_dict)

        data_dict2 = {
            "code": RET.OK,
            "address" : {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id,
            }
        }

        return http.JsonResponse(data_dict2)



class AddressesUpdateView(View):

    def put(self,request, address_id):
        data_dict = json.loads(request.body.decode())
        title = data_dict.get("title")
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        if not all([title, receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({"code": RET.PARAMERR, "errmsg": "参数不正确"})

        data_dict["user_id"] = request.user.id
        #del data_dict["id"]
        del data_dict['province']
        del data_dict['city']
        del data_dict['district']
        ret = Address.objects.filter(id=address_id).update(**data_dict)
        address = Address.objects.get(id=address_id)

        data_dict2 = {
            "code": RET.OK,
            "address": {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id,
            }
        }

        return http.JsonResponse(data_dict2)


    def delete(self,request, address_id):
        try:
            Address.objects.filter(id=address_id).update(is_deleted=True)
        except:
            return http.JsonResponse({"code": RET.DBERR, "errmsg": "删除失败"})

        return http.JsonResponse({"code": RET.OK, "errmsg": "删除成功"})


class AddressesDefaultView(View):
    def put(self,request, address_id):
        try:
            request.user.default_address_id = address_id
            request.user.save()
        except:
            return http.JsonResponse({"code": RET.DBERR, "errmsg":"设置失败"})

        return http.JsonResponse({"code": RET.OK, "errmsg": "修改成功"})


class AddressTitleView(View):
    def put(self,request, address_id):
        title = json.loads(request.body.decode()).get("title")
        if not title:
            return http.JsonResponse({"code": RET.PARAMERR, "errmsg":"参数不正确"})

        Address.objects.filter(id=address_id).update(title=title)
        return http.JsonResponse({"code": RET.OK, "errmsg": "title修改成功"})

class UserPassWordView(View):
    def get(self,request):
        return render(request, 'user_center_pass.html')

    def post(self,request):
        old_pwd = request.POST.get("old_pwd")
        new_pwd = request.POST.get("new_pwd")
        new_cpwd = request.POST.get("new_cpwd")

        if not all([old_pwd, new_pwd, new_cpwd]):
            return render(request, 'user_center_pass.html')

        if new_pwd != new_cpwd:
            return render(request, 'user_center_pass.html')

        if old_pwd == new_pwd:
            return render(request, 'user_center_pass.html')

        if not request.user.check_password(old_pwd):
            return render(request, 'user_center_pass.html')

        request.user.set_password(new_pwd)
        request.user.save()

        response = redirect('/login')
        logout(request)
        response.delete_cookie('username')
        return response








